// Burner Input Constant dialog module
#include "burner.h"

HWND hInpcDlg = NULL;								// Handle to the Input Dialog
unsigned int inpcInput = 0;							// The input number we are redefining

static HWND hValue = NULL;							// Handle to value edit control
static GameInp* pgi = NULL;							// Current GameInp

static int inpcInit()
{
	hValue = GetDlgItem(hInpcDlg, IDC_INPC_VALUE);	// Get Edit controls

	// Get the extra info about the input
	struct BurnInputInfo bii;
	memset(&bii, 0, sizeof(bii));
	BurnDrvGetInputInfo(&bii, inpcInput);
	if (bii.szName == NULL) {
		bii.szName= "";
	}

	// Set the dialog title
	wchar_t newTitle[512];
	_snwprintf(newTitle, sizearray(newTitle), L"%hs", bii.szName);
	SetWindowText(hInpcDlg, newTitle);

	pgi = NULL;
	if (inpcInput >= gameInpCount) {				// input out of range
		return 1;
	}
	pgi = gameInput + inpcInput;

	// Get current constant
	int current = 0;
	if (pgi->nInput == GIT_CONSTANT) {
		current = pgi->Input.Constant.nConst;
	}
	swprintf(newTitle, L"0x%.2X", current);
	SetWindowText(hValue, newTitle);

	return 0;
}

static int inpcExit()
{
	pgi = NULL;
	hValue = NULL;
	hInpcDlg = NULL;

	return 0;
}

static INT_PTR CALLBACK inpcDialogProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM /*lParam*/)
{
	if (msg == WM_INITDIALOG) {						// 1 = we didn't set focus?
		hInpcDlg = hDlg;
		inpcInit();

		return 1;
	}
	if (msg == WM_CLOSE){
		DestroyWindow(hInpcDlg);
		dialogManager.remove(IDD_INPC);
		return 0;
	}
	if (msg == WM_DESTROY) {
		inpcExit();

		return 0;
	}

	if (msg == WM_COMMAND) {
		int Id = LOWORD(wParam);
		int Notify = HIWORD(wParam);
		if (Id == IDOK     && Notify == BN_CLICKED) {		// OK = close
			SendMessage(hDlg, WM_CLOSE, 0, 0);
			return 0;
		}
		if (Id == IDCANCEL && Notify == BN_CLICKED) {		// cancel = close
			SendMessage(hDlg, WM_CLOSE, 0, 0);
			return 0;
		}

		if (Id == IDC_INPC_VALUE && Notify == EN_CHANGE) {
			// Edit box may have been changed
			if (pgi == NULL) {
				return 0;
			}

			wchar_t newText[32] = L"";
			GetWindowText(hValue, newText, sizearray(newText));

			// Set new constant
			pgi->nInput = GIT_CONSTANT;
			int val = wcstol(newText, NULL, 0);
			pgi->Input.Constant.nConst = (unsigned char)val;

			inpdListMake(0);								// refresh view

			return 0;
		}
	}

	return 0;
}

int inpcCreate()
{
	dialogManager.remove(IDD_INPC);
	DestroyWindow(hInpcDlg);
	hInpcDlg = NULL;

	hInpcDlg = localiseCreateDialog(IDD_INPC, dialogManager.get(IDD_INPD), (DLGPROC)inpcDialogProc);
	if (hInpcDlg == NULL) {
		return 1;
	}
	dialogManager.add(IDD_INPC, hInpcDlg);

	wndInMid(hInpcDlg, dialogManager.get(IDD_INPD));
	ShowWindow(hInpcDlg, SW_NORMAL);

	return 0;
}
